package cn.maihe.elg.operation.centers.follow.auth;

import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description
 * @Author caixh
 * @Date 2021/9/16.
 */
public class AuthHelper {

    public static String getSortString(Map<String,String> params){
        if(params==null || params.size()<1){
            return "";
        }
        Map<String, String> sorted = new TreeMap<>();
        params.forEach( (k, v) -> {
                sorted.put(k, v);
        });
        StringBuilder builder = new StringBuilder();
        sorted.forEach((k, v) -> {
            builder.append(k).append("=").append(v).append("&");
        });
        builder.deleteCharAt(builder.length()-1);
        return builder.toString();
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes("UTF-8"));
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte message : messageDigest) {
                String shaHex = Integer.toHexString(message & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }

                hexString.append(shaHex);
            }
            return hexString.toString().toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getTimestamp() {
        String timestamp = String.valueOf(System.currentTimeMillis());
        int length = timestamp.length();
        if (length > 3) {
            return timestamp.substring(0,length-3);
        } else {
            return "0";
        }

    }
}
